#include "globals.h"

// Global objects
ExceptionHandler err;
ImageManager     imageManager;
TiXmlDocument    sysDoc(RESOURCE_DIRECTORY CONFIG);
TiXmlElement*    sysXml;

vector<string> getDirContents(string directoryName) {
    DIR *dir;
    struct dirent *ent;
    vector<string> contents;
    
    dir = opendir (directoryName.c_str());
    if (dir != NULL) {
        while ((ent = readdir (dir)) != NULL) {
            // Current and parent directories are not added
            if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0) {
                contents.push_back(ent->d_name);
            }
        }
        
        closedir (dir);
    } else {
        throw "Couldn't open directory";
    }
    
    return contents;
}

TiXmlElement* getChildElementbyName(string name, TiXmlElement* parent) {
    TiXmlElement* child = parent->FirstChildElement();
    
    do {
        if (name.compare(child->Attribute("name")) == 0) {
            return child;
        } else {
            child = parent->IterateChildren(child)->ToElement();
        }
    } while (child);
    
    return NULL;
}

Color getColorFromXml(TiXmlElement* xml) {
    return Color(Chameleon(xml->Attribute("red")),
                 Chameleon(xml->Attribute("green")),
                 Chameleon(xml->Attribute("blue")));
}

void* callPython(string filename, string funcName) {
    // Initialize python
    Py_Initialize();
    PyObject* pModule  = PyImport_AddModule("__main__");
    PyObject* pDict    = PyModule_GetDict(pModule);
    FILE*     pFile    = fopen(filename.c_str(), "r");
    
    // Map variables TO python
    PyObject* var = PyString_FromString("asdf");
    PyDict_SetItemString(pDict, "var", var);
    Py_DecRef(var);
    
    // Run script
    PyRun_File(pFile, filename.c_str(), Py_file_input, pDict, pDict);
    
    // Map variables FROM python
    PyObject* result  = PyDict_GetItemString(pDict, "result");
    void* resultValue = new long(PyInt_AS_LONG(result));
    
    // Kill python
    Py_Finalize();
    
    return resultValue;
}